#!/bin/bash

set -e

# Get the directory where the script is located (must be done before any cd commands)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [ $# -lt 1 ]; then
    echo "Usage: $0 <PR_ID> [WORK_DIR]"
    echo "Example: $0 123"
    echo "Example: $0 123 /path/to/workdir"
    exit 1
fi

PR_ID="$1"
WORK_DIR="${2:-.}"
REPO_DIR="pqcp"
BRANCH_NAME="pr-$PR_ID"
REVIEW_FILE="pr-$PR_ID-review.md"

echo "Starting PR review process for PR ID: $PR_ID"

# Create and change to working directory
if [ ! -d "$WORK_DIR" ]; then
    echo "Creating working directory: $WORK_DIR"
    mkdir -p "$WORK_DIR"
fi

echo "Changing to working directory: $WORK_DIR"
cd "$WORK_DIR"

# Step 1: Remove existing openhitls directory if exists, then clone
if [ -d "$REPO_DIR" ]; then
    echo "Removing existing openhitls directory..."
    rm -rf "$REPO_DIR"
fi

git clone https://gitcode.com/openHiTLS/pqcp.git

# Step 2: Enter repo directory and fetch PR
echo "Fetching PR $PR_ID..."
cd "$REPO_DIR"

# Fetch the PR
git fetch origin "refs/merge-requests/$PR_ID/head:$BRANCH_NAME"

# Switch to the PR branch
git checkout "$BRANCH_NAME"

echo "Successfully fetched and checked out PR $PR_ID"

# Step 3: Copy CLAUDE.md to repository
echo "Copying CLAUDE.md to repository..."
CLAUDE_FILE="$SCRIPT_DIR/CLAUDE.md"
echo "Script directory: $SCRIPT_DIR"
echo "Looking for CLAUDE.md at: $CLAUDE_FILE"
echo "Current directory: $(pwd)"

if [ -f "$CLAUDE_FILE" ]; then
    cp "$CLAUDE_FILE" .
    echo "CLAUDE.md copied successfully to $(pwd)/CLAUDE.md"
    # Verify the copy was successful
    if [ -f "CLAUDE.md" ]; then
        echo "Verification: CLAUDE.md exists in repository root"
    else
        echo "Error: Failed to copy CLAUDE.md to repository root"
    fi
else
    echo "Error: CLAUDE.md not found at $CLAUDE_FILE"
    echo "Available files in script directory:"
    ls -la "$SCRIPT_DIR"
    exit 1
fi

# Step 4: Perform review
echo "Performing code review..."
claude --dangerously-skip-permissions -p "ultrathink 根据git diff main…$BRANCH_NAME 的全部差异进行review，代码问题要具体，明确有问题的逻辑和代码行，如果确实没有问题也不要乱写，要准确，特别是关注安全性，减少总结性的言论，聚焦代码的功能、架构、安全和规范性，生成中文报告 $REVIEW_FILE 报告最后的作者为openHiTLS Team"

echo "Review complete! Report generated: $REVIEW_FILE"
echo "PR $PR_ID review process finished successfully."
